package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/*
  聊天室的服务端
 */
public class Server {
    private ServerSocket serverSocket;

    //保存所有客户端的输出流用于广播消息
    //private PrintWriter[] allOut = {};
    private Collection<PrintWriter> allOut = new ArrayList<>();


    public Server(){
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println(socket.getInetAddress().getHostAddress()+"已连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run() {
            PrintWriter pw = null;
            try {
                //通过刚接受连接的socket,获取输入流来读取该客户端发送过来的消息
                InputStream sis = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(sis, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //通过socket获取输出流给客户端发消息
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                //将该输出流存入到共享数组allOut中
                //synchronized (this){}//不同线程调用不同的clientHandler的run方法，因此run方法中的this(ClientHandler不是同一个)
                //synchronized (allOut){}//线程进入到同步块中会创建新的数组对象赋值给allOut，导致其如果作为对象会发生改变
                //将该输出流存入到共享数组allOut中
                //1.将allOut数组扩容
                synchronized (Server.this) {
                    allOut.add(pw);
                    sendMessage(host + "上线了,当前在在线人数:" + allOut.size());
                }
                /*
                    使用readLine读取远端计算机发送过来消息时,对应断开操作不同,这里体现的结果不同,
                    可能存在如下情况:
                    1:当远端计算机调用socket.close(),此时对方会进行正常的TCP四次挥手断开连接.
                      那么readLine方法会返回值为null.
                    2:readLine()方法抛出异常:java.net.SocketException: connection reset
                      说明客户端是非正常退出的(没有进行TCP挥手操作)
                 */
                String line;
                while ((((line = br.readLine()) != null)) ) {
                    sendMessage(line);
                }
            }catch (IOException e) {
                //e.printStackTrace();
            }finally {
                //处理客户端断开连接后的操作
                //将pw从数组allOut中删除
                synchronized (Server.this){
                    allOut.remove(pw);
                }
                sendMessage(host+"下线了,当前在线人数:"+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void sendMessage(String message){
            System.out.println(host+"说:" + message);
            //将消息发送给客户端
            synchronized (Server.this) {
                for (PrintWriter data : allOut) {
                    data.println(host + ":说:" + message);
                }
            }
        }
    }
}
